<template>
  <el-card>
    <el-alert
      title="添加商品信息"
      type="info"
      center
      show-icon
      :closable="false"
    />
    <el-steps
      style="max-width: 600px"
      :space="200"
      :active="activeIndex - 0"
      finish-status="success"
      class="steps-demo1"
      align-center
    >
      <el-step title="基本信息" />
      <el-step title="商品参数" />
      <el-step title="商品属性" />
      <el-step title="商品图片" />
      <el-step title="商品内容" />
    </el-steps>
    <el-form
      ref="addFormRef"
      :model="addForm"
      :rules="addFormrules"
      label-width="auto"
      :size="formSize"
      status-icon
      label-position="top"
      class="demo-form"
    >
      <el-tabs
        :before-leave="beforeTabLeave"
        v-model="activeIndex"
        tab-position="left"
        class="demo-tabs"
        @tab-click="tabClick"
      >
        <el-tab-pane label="基本信息" name="0">
          <el-form-item label="商品名称" prop="goods_name">
            <el-input v-model="addForm.goods_name" />
          </el-form-item>
          <el-form-item label="商品价格" prop="goods_price" type="number">
            <el-input v-model="addForm.goods_price" />
          </el-form-item>
          <el-form-item label="商品数量" prop="goods_number" type="number">
            <el-input v-model="addForm.goods_number" />
          </el-form-item>
          <el-form-item label="商品重量" prop="goods_weight" type="number">
            <el-input v-model="addForm.goods_weight" />
          </el-form-item>
          <el-form-item label="商品分类" prop="goods_cat">
            <span class="cat_right">选择商品分类</span>
            <el-cascader
              expand-trigger="hover"
              v-model="addForm.goods_cat"
              :options="CateList"
              :props="cateprop"
              @change="handleChange"
              placeholder="请选择商品分类"
            />
          </el-form-item>
          <el-form-item label="商品介绍" prop="goods_introduce">
            <el-input v-model="addForm.goods_introduce" />
          </el-form-item>
        </el-tab-pane>
        <el-tab-pane label="商品参数" name="1">
          <el-form-item
            :label="item.attr_name"
            v-for="item in manyTabData"
            :key="item.attr_id"
          >
            <el-checkbox-group v-model="item.attr_vals">
              <el-checkbox
                :label="cb"
                v-for="(cb, index) in item.attr_vals"
                :key="index"
                border
              />
            </el-checkbox-group>
          </el-form-item>
        </el-tab-pane>
        <el-tab-pane label="商品属性" name="2">
          <el-form-item
            :label="item.attr_name"
            v-for="item in onlyTabData"
            :key="item.attr_id"
          >
            <el-input v-model="item.attr_vals" />
          </el-form-item>
        </el-tab-pane>
        <el-tab-pane label="商品图片" name="3">
          <el-upload
            :action="uploadURL"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            list-type="picture"
            :headers="headerObj"
            :on-success="handleSuccess"
          >
            <el-button type="primary">点击上传图片</el-button>
          </el-upload>
        </el-tab-pane>
        <el-tab-pane label="商品内容" name="4"> </el-tab-pane>
      </el-tabs>
    </el-form>
  </el-card>
  <el-dialog
    v-model="previewVisible"
    title="图片预览"
    width="50%"
    height="50%"
    :before-close="handleClose"
  >
    <img class="dialogImg" width="100%" :src="previewPath" alt="" />
  </el-dialog>
</template>

<script setup>
import { ref } from 'vue'
import { getCateLists } from '@/api/goods'
import { ElMessage } from 'element-plus'
import { getCategory } from '@/api/categories'
const activeIndex = ref(0)
const headerObj = ref({
  Authorization: localStorage.getItem('token')
})
const addForm = ref({
  goods_name: '',
  goods_price: '',
  goods_weight: '',
  goods_number: '',
  goods_cat: [],
  goods_introduce: '',
  pics: []
})
const addFormrules = ref({
  goods_name: [
    { required: true, message: '请输入商品名称', trigger: 'blur' },
    { min: 3, max: 50, message: '长度在 3 到 50 个字符', trigger: 'blur' }
  ],
  goods_price: [
    { required: true, message: '请输入商品价格', trigger: 'blur' },
    { min: 0, max: 10000, message: '价格在 0 到 10000 之间', trigger: 'blur' }
  ],
  goods_weight: [
    { required: true, message: '请输入商品重量', trigger: 'blur' },
    { min: 0, max: 10000, message: '重量在 0 到 10000 之间', trigger: 'blur' }
  ],
  goods_number: [
    { required: true, message: '请输入商品数量', trigger: 'blur' },
    { min: 0, max: 10000, message: '数量在 0 到 10000 之间', trigger: 'blur' }
  ],
  goods_cat: [{ required: true }],
  goods_introduce: [{ required: false }]
})
const CateList = ref([])
const cateprop = ref({
  label: 'cat_name',
  value: 'cat_id',
  children: 'children'
})
const manyTabData = ref([])
const onlyTabData = ref([])
const uploadURL = ref('http://127.0.0.1:8888/api/private/v1/upload')
// 获取商品分类
const getCateList = async () => {
  const res = await getCateLists()
  CateList.value = res
}
getCateList()
// 是否是三级选择
const handleChange = (value) => {
  console.log(value)
  if (addForm.value.goods_cat.length !== 3) {
    addForm.value.goods_cat = []
  }
}
const beforeTabLeave = (activeKey, oldActiveKey) => {
  if (oldActiveKey === '0' && addForm.value.goods_cat.length !== 3) {
    ElMessage.error('请先选择商品分类！')
    return false
  } else {
    return true
  }
}
const handleSuccess = (res) => {
  console.log(res)
  const picInfo = {
    pic: res.data.tmp_path
  }
  addForm.value.pics.push(picInfo)
  console.log(addForm.value.pics)
}
const tabClick = async () => {
  if (activeIndex.value === '1') {
    const res = await getCategory(addForm.value.goods_cat[2], 'many')
    res.forEach((element) => {
      element.attr_vals =
        element.attr_vals.length === 0 ? [] : element.attr_vals.split(',')
    })
    manyTabData.value = res
  } else if (activeIndex.value === '2') {
    const res = await getCategory(addForm.value.goods_cat[2], 'only')
    onlyTabData.value = res
  }
}
const previewPath = ref('')
const previewVisible = ref(false)
// 图片预览
const handlePreview = (file) => {
  console.log(file)
  previewPath.value = file.response.data.url
  previewVisible.value = true
}
// 删除图片
const handleRemove = (file) => {
  const tmpPath = file.response.data.tmp_path
  const index = addForm.value.pics.findIndex((item) => item.pic === tmpPath)
  addForm.value.pics.splice(index, 1)
  console.log(addForm.value.pics)
}
</script>

<style lang="scss" scoped>
.steps-demo1 {
  margin: 50px auto 0;
}
.demo-form {
  margin: 20px auto 0;
}
.cat_top {
  margin: 35px;
}
.cat_right {
  margin-right: 20px;
}
.el-checkbox {
  margin: 0 10px 0 0 !important;
}
.dialogImg {
  width: 100%;
  height: 100%;
}
</style>
